<template>
    <a-select class="custom-select" v-model:value="innerValue" :options="options"
        :disabled="disabled" :allowClear="allowClear" :mode="props.mode" :showSearch="showSearch"
        :filterOption="remote ? false : filterOption" @change="handleChange" @search="handleSearch"
        @dropdownVisibleChange="handleDropdownVisibleChange" v-bind="$attrs">
        <template #placeholder>
            <span class="placeholder">{{ placeholder || '请选择'}}</span>
        </template>
        <template v-if="loading" #notFoundContent>
            <a-spin size="small" />
        </template>
    </a-select>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'

interface Props {
    value: string | number | any[] | undefined
    options: Record<string, any>[]
    placeholder?: string
    disabled?: boolean
    allowClear?: boolean
    mode?: 'multiple' | 'tags' | 'combobox' | any
    showSearch?: boolean
    remote?: boolean
    remoteMethod?: Function
    loading?: boolean
    styles?: Record<string, any>
}
const props = withDefaults(defineProps<Props>(), {
    disabled: false,
    allowClear: false,
    showSearch: true,
    styles: () => ({
        width: '100%'
    })
})

const emit = defineEmits(['update:value', 'change', 'search'])

const innerValue = ref<any>(props.value)

// 监听外部value变化
watch(() => props.value, (newVal) => {
    innerValue.value = newVal
})

// 处理change事件
const handleChange = (value, option) => {
    emit('update:value', value)
    emit('change', value, option)
}

// 处理搜索事件
const handleSearch = (value) => {
    emit('search', value)
}

// 处理下拉框显示/隐藏
const handleDropdownVisibleChange = (open) => {
    if (open && props.remote && props.remoteMethod) {
        props.remoteMethod('')
    }
}

// 本地筛选选项
const filterOption = (input, option) => {
    return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
</script>

<style scoped lang="less">
.placeholder {
    color: #6c768e;
}
</style>